/**
 * 
 */
package cn.com.winning.ecare.activity;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.achartengine.ChartFactory;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.TimeSeries;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.renderer.SimpleSeriesRenderer;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint.Align;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import cn.com.winning.ecare.common.MyApplication;
import cn.com.winning.ecare.common.MyTimeUtil;
import cn.com.winning.ecare.utils.DisplayUtil;
import cn.com.winning.ecare.utils.HTTPGetTool;
import cn.com.winning.ecare.utils.URLUtils;
import cn.com.winning.ecare.widgets.CustomProgressDialog;

/**健康测评-血糖历史
 * @author Administrator
 */
public class XtHistory extends Activity

{
	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */

	private XtHistory oThis = this;
	private static final int SEARCHMSG = 0;
	private static final int SEARCHERRMSG = 1;
	MyApplication myApplication;
	int screenheight;
	int screenwidth;
	CustomProgressDialog proDialog;// 加载框
	List<Date[]> dates = new ArrayList<Date[]>();
	List<double[]> values = new ArrayList<double[]>();
	LinearLayout lineChartContainer;
	private ImageView menu_img;
	private ImageButton mainselected;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.xthistoryactivity);
		findView();
		setOnClick();
		myApplication = (MyApplication) getApplication();
		myApplication.addActivity(this);
		// 获取屏幕分辨率
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		screenheight = dm.heightPixels;
		screenwidth = dm.widthPixels;
		if (proDialog == null)
		{
			proDialog = CustomProgressDialog.createDialog(oThis);
		}
		proDialog.setMessage("数据加载中");
		proDialog.show();
		proDialog.setCanceledOnTouchOutside(true);
		new Thread(new InitData()).start();

	}

	private void findView()
	{
		lineChartContainer = (LinearLayout) findViewById(R.id.lineChart_container);
		menu_img = (ImageView) this.findViewById(R.id.menuButton);
		mainselected = (ImageButton) this.findViewById(R.id.mainselected);
	}

	private void setOnClick()
	{
		menu_img.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View view)
			{
				oThis.onBackPressed();
			}
		});
		mainselected.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View view)
			{
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(oThis, Mainmean.class);
				startActivity(intent);
				oThis.finish();
			}
		});
	}

	private Handler myHandler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			switch (msg.what)
			{
				case SEARCHMSG:
					if (proDialog != null && proDialog.isShowing())
					{
						proDialog.dismiss();
					}
					if (msg.obj != null)
					{
						Map<String, Object> map = (Map<String, Object>) msg.obj;
						dates = (List<Date[]>) map.get("date");
						values = (List<double[]>) map.get("data");
					}
					init();
					break;
				case SEARCHERRMSG:
					if (proDialog != null && proDialog.isShowing())
					{
						proDialog.dismiss();
					}
					if (msg.obj != null)
					{
						Toast.makeText(oThis, (String) msg.obj, Toast.LENGTH_SHORT).show();
					}
				default:
					break;
			}
		}
	};

	private void init()
	{
		Calendar calendarn = Calendar.getInstance();
		calendarn.set(Calendar.DAY_OF_MONTH, calendarn.getActualMinimum(Calendar.DAY_OF_MONTH));
		Calendar calendarm = Calendar.getInstance();
		calendarm.set(Calendar.DAY_OF_MONTH, calendarm.getActualMaximum(Calendar.DAY_OF_MONTH));
		String[] titles = new String[] { "血糖" };
		int[] colors = new int[] { Color.parseColor("#2d6d98") };
		PointStyle[] styles = new PointStyle[] { PointStyle.DIAMOND };
		XYMultipleSeriesRenderer renderer = buildRenderer(colors, styles);
		setChartSettings(renderer, "", "", "mmol/L", dates.get(0)[0].getTime(),
				dates.get(0)[dates.get(0).length - 1].getTime(), 0.5, 17.7, Color.GRAY, Color.LTGRAY);
		// XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer(2);
		// setRenderer(renderer, colors, styles);
		renderer.setPanEnabled(true, false); // 设置x,y坐标轴不会因用户划动屏幕而移动
		renderer.setMarginsColor(Color.argb(0, 0xff, 0, 0));// 设置4边留白透明
		renderer.setBackgroundColor(Color.TRANSPARENT); // 设置背景色透明
		renderer.setApplyBackgroundColor(true); // 使背景色生效
		renderer.setXLabels(5);// 设置X轴显示12个点，根据setChartSettings的最大值和最小值自动计算点的间隔
		renderer.setYLabels(10);// 设置y轴显示10个点,根据setChartSettings的最大值和最小值自动计算点的间隔
		renderer.setXLabelsAlign(Align.RIGHT);// 刻度线与刻度标注之间的相对位置关系
		renderer.setYLabelsAlign(Align.CENTER);// 刻度线与刻度标注之间的相对位置关系
		// render.setZoomButtonsVisible(true);// 是否显示放大缩小按钮
		renderer.setShowGrid(true);// 是否显示网格
		renderer.setGridColor(Color.parseColor("#ebebeb"));// 设置网格颜色
		renderer.setAxesColor(Color.parseColor("#ebebeb"));// 设置X.y轴颜色
		renderer.setFitLegend(true);// 设置自动按比例缩放
		renderer.setChartTitleTextSize(DisplayUtil.dip2px(oThis, 15));
		renderer.setTextTypeface("sans_serif", Typeface.BOLD);
		renderer.setLabelsTextSize(DisplayUtil.dip2px(oThis, 15));
		renderer.setAxisTitleTextSize(DisplayUtil.dip2px(oThis, 15));
		renderer.setLegendTextSize(DisplayUtil.dip2px(oThis, 15));
		renderer.setBackgroundColor(Color.parseColor("#FFFFFF"));
		renderer.setApplyBackgroundColor(true);
		// renderer.setZoomButtonsVisible(true);
		int length = renderer.getSeriesRendererCount();
		for (int i = 0; i < length; i++)
		{
			// XYSeriesRenderer xyRenderer = (XYSeriesRenderer)
			// renderer.getSeriesRendererAt(i);
			// xyRenderer.setLineWidth(3f);
			// xyRenderer.setChartValuesTextSize(20f);
			// xyRenderer.setFillPoints(true);
			SimpleSeriesRenderer seriesRenderer = renderer.getSeriesRendererAt(i);
			seriesRenderer.setDisplayChartValues(true);
			((XYSeriesRenderer) seriesRenderer).setFillPoints(true);
			((XYSeriesRenderer) seriesRenderer).setLineWidth(DisplayUtil.dip2px(oThis, 2));
			seriesRenderer.setChartValuesTextSize(DisplayUtil.dip2px(oThis, 15));
			// xyRenderer.setDisplayChartValuesDistance(30);
		}
		// renderer.setYLabels(10);
		// renderer.setXRoundedLabels(false);
		View chart = ChartFactory.getTimeChartView(oThis, buildDateDataset(titles, dates, values), renderer, "MM/dd");
		lineChartContainer.addView(chart);
	}

	/**
	 * Builds an XY multiple series renderer.
	 * 
	 * @param colors
	 *        the series rendering colors
	 * @param styles
	 *        the series point styles
	 * @return the XY multiple series renderers
	 */
	protected XYMultipleSeriesRenderer buildRenderer(int[] colors, PointStyle[] styles)
	{
		XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
		setRenderer(renderer, colors, styles);
		return renderer;
	}

	protected void setRenderer(XYMultipleSeriesRenderer renderer, int[] colors, PointStyle[] styles)
	{
		renderer.setAxisTitleTextSize(16);
		renderer.setChartTitleTextSize(20);
		renderer.setLabelsTextSize(15);
		renderer.setLegendTextSize(15);
		renderer.setPointSize(5f);
		renderer.setMargins(new int[] { DisplayUtil.dip2px(oThis, 20), DisplayUtil.dip2px(oThis, 30),
				DisplayUtil.dip2px(oThis, 15), DisplayUtil.dip2px(oThis, 20) });
		int length = colors.length;
		for (int i = 0; i < length; i++)
		{
			XYSeriesRenderer r = new XYSeriesRenderer();
			r.setColor(colors[i]);
			r.setPointStyle(styles[i]);
			renderer.addSeriesRenderer(r);
		}
	}

	/**
	 * Builds an XY multiple time dataset using the provided values.
	 * 
	 * @param titles
	 *        the series titles
	 * @param xValues
	 *        the values for the X axis
	 * @param yValues
	 *        the values for the Y axis
	 * @return the XY multiple time dataset
	 */
	protected XYMultipleSeriesDataset buildDateDataset(String[] titles, List<Date[]> xValues, List<double[]> yValues)
	{
		XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
		int length = titles.length;
		for (int i = 0; i < length; i++)
		{
			TimeSeries series = new TimeSeries(titles[i]);
			Date[] xV = xValues.get(i);
			double[] yV = yValues.get(i);
			int seriesLength = xV.length;
			for (int k = 0; k < seriesLength; k++)
			{
				series.add(xV[k], yV[k]);
			}
			dataset.addSeries(series);
		}
		return dataset;
	}

	protected void setChartSettings(XYMultipleSeriesRenderer renderer, String title, String xTitle, String yTitle,
			double xMin, double xMax, double yMin, double yMax, int axesColor, int labelsColor)
	{
		renderer.setChartTitle(title);
		renderer.setXTitle(xTitle);
		renderer.setYTitle(yTitle);
		renderer.setXAxisMin(xMin);
		renderer.setXAxisMax(xMax);
		renderer.setYAxisMin(yMin);
		renderer.setYAxisMax(yMax);
		renderer.setAxesColor(axesColor);
		renderer.setLabelsColor(labelsColor);
	}

	class InitData implements Runnable
	{
		/*
		 * (non-Javadoc)
		 * 
		 * @see java.lang.Runnable#run()
		 */
		@Override
		public void run()
		{
			Looper.prepare();
			initData();
			Looper.loop();
		}
	}

	private void initData()
	{
		Message message = myHandler.obtainMessage();
		List<NameValuePair> ls = new ArrayList<NameValuePair>();
		ls.add(new BasicNameValuePair("username", myApplication.getAccount()));
		JSONObject json = HTTPGetTool.getTool().post(URLUtils.HOST + URLUtils.YXTXTRECORDSFINDDATA, ls);
		JSONArray jsonArray = null;
		List<Date[]> dates = new ArrayList<Date[]>();
		List<double[]> values = new ArrayList<double[]>();
		Date[] date = {};
		double[] xt = {};
		Map<String, Object> map = new HashMap<String, Object>();
		try
		{
			if (json != null)
			{
				jsonArray = json.getJSONArray("listrecords");
				if (jsonArray.length() > 0)
				{
					date = new Date[jsonArray.length()];
					xt = new double[jsonArray.length()];
					for (int i = 0; i < jsonArray.length(); i++)
					{
						JSONObject jsonObject = jsonArray.getJSONObject(i);
						date[i] = MyTimeUtil.strToDate(MyTimeUtil.yyyy_MM_dd, jsonObject.getString("clrq"));
						xt[i] = Double.valueOf(jsonObject.getString("xt"));
					}
					dates.add(date);
					values.add(xt);
					map.put("date", dates);
					map.put("data", values);
					message.obj = map;
					message.what = SEARCHMSG;
				}
				else
				{
					message.obj = "暂无历史数据";
					message.what = SEARCHERRMSG;
				}

			}
			else
			{
				message.obj = "数据获取失败";
				message.what = SEARCHERRMSG;
			}

		}
		catch (Exception e)
		{
			message.obj = "数据获取失败";
			message.what = SEARCHERRMSG;
		}
		myHandler.sendMessage(message);
	}

}
